EventFormattingAgent: Enable access to upstream agent info via "agent".

With this enhancement you can, for example, embed the site URL in an
event created by WebsiteAgent by interpolating like
"{{agent.options.url}}", or add a message prefix depending on the type
of upstream agent using the "case" construct of Liquid.

Akinori MUSHA 10 years ago
parent
commit
e55bb4ac3d
2 changed files with 25 additions and 1 deletions
  1. 22 0
      app/models/agent.rb
  2. 3 1
      app/models/agents/event_formatting_agent.rb

+ 22 - 0
app/models/agent.rb

@@ -382,3 +382,25 @@ class Agent < ActiveRecord::Base
382 382
     handle_asynchronously :async_check
383 383
   end
384 384
 end
385
+
386
+class AgentDrop < Liquid::Drop
387
+  def initialize(object)
388
+    @object = object
389
+  end
390
+
391
+  def type
392
+    @object.short_type
393
+  end
394
+
395
+  %w[options memory name sources receivers schedule disabled keep_events_for propagate_immediately].each { |attr|
396
+    define_method(attr) {
397
+      @object.__send__(attr)
398
+    }
399
+  }
400
+
401
+  class ::Agent
402
+    def to_liquid
403
+      AgentDrop.new(self)
404
+    end
405
+  end
406
+end

+ 3 - 1
app/models/agents/event_formatting_agent.rb

@@ -28,6 +28,8 @@ module Agents
28 28
             "subject": "{{data}}"
29 29
           }
30 30
 
31
+      The upstream agent of each received event is accessible via the key `agent`, which has the following attributes: #{''.tap { |s| s << AgentDrop.instance_methods(false).map { |m| "`#{m}`" }.join(', ') }}.
32
+
31 33
       Have a look at the [Wiki](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to learn more about liquid templating.
32 34
 
33 35
       Events generated by this possible Event Formatting Agent will look like:
@@ -105,7 +107,7 @@ module Agents
105 107
     def receive(incoming_events)
106 108
       incoming_events.each do |event|
107 109
         agent = Agent.find(event.agent_id)
108
-        payload = perform_matching(event.payload)
110
+        payload = perform_matching({ 'agent' => agent }.update(event.payload))
109 111
         opts = interpolated(payload)
110 112
         formatted_event = opts['mode'].to_s == "merge" ? event.payload.dup : {}
111 113
         formatted_event.merge! opts['instructions']